/**
 * 
 */
package com.kingre.et.action;

import java.io.IOException;

import javax.mail.MessagingException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.kingre.et.model.User;
import com.kingre.et.service.IUserService;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Jingui Yu
 * 
 */
public class ResetPwdAction extends ActionSupport {
    private static final long serialVersionUID = -5752903415402398557L;
    private static final Logger logger = Logger.getLogger(ResetPwdAction.class);
    @Autowired
    private IUserService userService;
    private Integer uid;
    private String email;
    private String password;

    @Override
    public String execute() throws IOException, MessagingException {
        logger.debug("email=" + email);
        if (!userService.emailExist(email)) {
            addFieldError("dd", getText("email.no.exist"));
            return INPUT;
        }
        User user = userService.getUserByEmail(email);
        userService.sendMail(
                email,
                getText("reset.email.subject"),
                getText("reset.email.message",
                        new String[] { user.getName(), user.getId().toString(), user.getEmail() }));
        return SUCCESS;
    }

    public String resetInput() {
        logger.debug("uid =" + uid);
        logger.debug("email =" + email);
        User user = userService.getUserByEmail(email);
        if (user == null || uid == null || user.getId().intValue() != uid.intValue())
            return INPUT;
        return SUCCESS;
    }

    public String resetCommit() {
        logger.debug("uid =" + uid);
        logger.debug("password =" + password);
        userService.updatePwd(uid, password);
        return SUCCESS;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email.replace("$", "@");
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
